package com.stalltea.easypool;

import java.util.LinkedList;

/**
 * @author yilvchangfa
 * @since 2021/11/30 16:34
 **/
public class ConnectionPool {

    private final LinkedList<Connection> pool = new LinkedList<>();

    public ConnectionPool(int initialSize) {
        if (initialSize <= 0) {
            return;
        }
        while (initialSize > 0) {
            pool.addLast(new Connection());
            initialSize--;
        }
    }

    public void releaseConnection(Connection connection) {
        if (null == connection) {
            return;
        }
        synchronized (pool) {
            pool.addLast(connection);
            pool.notifyAll();
        }
    }

    public Connection fetchConnection(long mills) throws InterruptedException {
        synchronized (pool) {
            if (mills <= 0) {
                while (pool.isEmpty()) {
                    pool.wait();
                }
                return pool.removeFirst();
            }
            long future = System.currentTimeMillis() + mills;
            while (pool.isEmpty() && future - System.currentTimeMillis() > 0) {
                pool.wait();
            }
            Connection result = null;
            if (!pool.isEmpty()) {
                result = pool.removeFirst();
            }
            return result;
        }
    }

}
